package br.mil.aer.pame;

import java.rmi.RemoteException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.tomasio.projects.organization.webservices.EfetivoWS;
import com.tomasio.projects.organization.webservices.EfetivoWSProxy;
import com.tomasio.projects.organization.webservices.FotoDTO;
import com.tomasio.projects.organization.webservices.MatriculaDTO;
import com.tomasio.projects.organization.webservices.PessoaDTO;
import com.tomasio.projects.organization.webservices.TelefoneDTO;

public class ImportFotoOnLoginAction extends Action {

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response)
			throws ActionException {
		EfetivoWS proxy = new EfetivoWSProxy();

		try {
			
			Long userIdObj = (Long) request.getAttribute(WebKeys.USER_ID);
			User user = UserLocalServiceUtil.getUserById(userIdObj);

			String s[] = user.getEmailAddress().split("@");
			String login = s[0];
			
			MatriculaDTO matricula = proxy.findMatriculaByLogin(login);
			
			if (matricula != null) {
				PessoaDTO pessoa = proxy.findPessoa(matricula.getPessoa()
						.getId());
				if(pessoa != null) {
					user.setJobTitle(matricula.getCargo());
					user.getBirthday().setTime(
							pessoa.getDataNascimento().getTimeInMillis());
					
					TelefoneDTO [] telefones = pessoa.getTelefones();
					if(telefones != null){
						
						for(int i=0; i < telefones.length; i++){
							System.out.println("interação" + i);
							TelefoneDTO telefone = telefones[i];
							if(telefone.getNumero().contains("2117")){
								user.setOpenId(
										telefone.getNumero().substring(5)
										);
								
							}
						}
					}
					
					//user.setFacebookId();
					//System.out.println("Versão Nova");
					FotoDTO foto = pessoa.getFotos()[0];
					if(foto != null){
						Long imageId = user.getPortraitId();
						if(imageId != null && imageId > 0){
							ImageLocalServiceUtil.updateImage(imageId,
									foto.getSource());
						}else{
				
							
							//Image image = ImageLocalServiceUtil.getImage(foto.getSource());
							Long pk = System.currentTimeMillis();
							ImageLocalServiceUtil.createImage(imageId);
							ImageLocalServiceUtil.updateImage(pk, foto.getSource());
							
							user.setPortraitId(pk);
						}
					}
					
					UserLocalServiceUtil.updateUser(user);
					
				}
			}
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
